//
//  ShopListController.m
//  waimai
//
//  Created by Mac on 11-12-30.
//  Copyright (c) 2011年 waimai. All rights reserved.
//






#import "ShopListController.h"
#import "CustomCell.h"
#import "DetailShopViewController.h"
#import "SectionHeaderController.h"
#import "Supplier.h"
#import "SupplierCategory.h"
#import "PublicFunction.h"
#import "UICustomImageView.h"
#import "Constants.h"

@interface ShopListController (private)
- (void)refresh;
- (void)stopLoading;
- (void)startLoading;
@end
@implementation ShopListController
@synthesize activityIndicatorView;
@synthesize typePickerView;
@synthesize addressPickerView;
@synthesize shopHoursPickerView;
@synthesize addressTestData;
@synthesize shopHoursTestData;



@synthesize supplierCategoryTag;


#define addressTag 1//地址按钮标签
#define typeTag 2//类型按钮标签
#define shopHoursTag 3//营业时间标签


- (void) initMembers{
    NSLog(@"jinrujinru");
    currentPage = 1;
    suppliers = [recieveDictionary objectForKey:@"Suppliers"];
    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;	
    if([appDelegate status])
    {
        //联网，添加到本地
        NSString *supplierCategoryTagString=[NSString stringWithFormat: @"%d", supplierCategoryTag]; 
        [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:supplierCategoryTagString sPage:@"1"];
    }

}

//用代码添加addressPickerView控件,初始位置在屏幕外
-(void) addAddressPickerView {
	if (addressPickerView == nil) {
		addressPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 460, 320, 460)];
		addressPickerView.delegate = self;
		addressPickerView.dataSource = self;
		addressPickerView.showsSelectionIndicator = YES;
		[self.view addSubview:addressPickerView];
		[addressPickerView release];
	}
}

//用代码添加typePickerView控件,初始位置在屏幕外
-(void) addTypePickerView {
	if (typePickerView == nil) {
		typePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 460, 320, 460)];
		typePickerView.delegate = self;
		typePickerView.dataSource = self;
		typePickerView.showsSelectionIndicator = YES;
		[self.view addSubview:typePickerView];
		[typePickerView release];
	}
}

//用代码添加shopHoursPickerView控件,初始位置在屏幕外
-(void) addShopHoursPickerView {
	if (shopHoursPickerView == nil) {
		shopHoursPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 460, 320, 460)];
		shopHoursPickerView.delegate = self;
		shopHoursPickerView.dataSource = self;
		shopHoursPickerView.showsSelectionIndicator = YES;
		[self.view addSubview:shopHoursPickerView];
		[shopHoursPickerView release];
	}
}

//初始化导航栏
-(void)initNav{
    //修改导航栏背景
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"001s.png"] forBarMetrics: UIBarMetricsDefault];
    //定义导航栏左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 54, 27)];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"navBtn.png"] forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"navBtn.png"] forState:UIControlStateHighlighted];
    [leftButton setTitle:@"首 页" forState:UIControlStateNormal]; 
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    
    [leftButton addTarget:self action:@selector(backButtonPressd:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton release];
    self.navigationItem.leftBarButtonItem = leftItem;
    [leftItem release];
}

//初始化选择条件按钮
-(void)initTypeBtn{
    //按钮区域背景
    UIImageView* bnView=[[UIImageView alloc] initWithFrame:CGRectMake(0,-5,320,50)];
    [bnView setImage:[UIImage imageNamed:@"btnBg1.png"]];
    [self.view addSubview:bnView];
    [bnView release];
    //初始化按钮    
    addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(5, 5, 100, 30);
    addBtn.tag=1;
    [addBtn setTitle:@"地区" forState:UIControlStateNormal];
    //设置文字居左，默认居中
    //    addBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    //详细设置文字位置，（上，左，下，右），初始值为居中左边
    [addBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    [addBtn setBackgroundImage:[UIImage imageNamed:@"btn1.png"] forState:UIControlStateNormal];
    addBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16]; 
    [addBtn addTarget:self action:@selector(showPickerViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    
    typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    typeBtn.frame = CGRectMake(110, 5, 100, 30);
    typeBtn.tag=2;
    [typeBtn setTitle:@"类型" forState:UIControlStateNormal];
    //详细设置文字位置，（上，左，下，右），初始值为居中左边
    [typeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    [typeBtn setBackgroundImage:[UIImage imageNamed:@"btn1.png"] forState:UIControlStateNormal];
    typeBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16]; 
    [typeBtn addTarget:self action:@selector(showPickerViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:typeBtn];
    
    timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    timeBtn.frame = CGRectMake(215, 5, 100, 30);
    timeBtn.tag=3;
    [timeBtn setTitle:@"营业情况" forState:UIControlStateNormal];
    //详细设置文字位置，（上，左，下，右），初始值为居中左边
    [timeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    [timeBtn setBackgroundImage:[UIImage imageNamed:@"btn1.png"] forState:UIControlStateNormal];
    timeBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16]; 
    [timeBtn addTarget:self action:@selector(showPickerViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:timeBtn];
    
    for(int i=0;i<3;i++){
        if(i==0){
            indexX=85;
        }
        else
        {
            indexX=indexX+105;
        }
        //icon
        UIImageView* iconView=[[UIImageView alloc] initWithFrame:CGRectMake(indexX,15,12,12)];
        [iconView setImage:[UIImage imageNamed:@"btnIco.png"]];
        [self.view addSubview:iconView];
        [iconView release];
    }
    
}

//初始化picker样式
-(void)initPickers{
    //隐藏pickerView上的横条和确定取消按钮
    tiaoImageView=[[UIImageView alloc]init];
    [tiaoImageView setImage:[UIImage imageNamed:@"blacktiao.PNG"]];
    [self.view addSubview:tiaoImageView];
    [tiaoImageView setHidden: YES];
    
    submitButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [submitButton setTitle:@"确定" forState:UIControlStateNormal];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitButton setBackgroundImage:[UIImage imageNamed:@"003.png"] forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(pickerEndButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitButton];
    [submitButton setHidden:YES];
    
    cancelButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"003.png"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(pickerCancelButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelButton];
    [cancelButton setHidden:YES];
}

//点击完成触发：
-(IBAction)pickerEndButtonPress:(id)sender
{
    NSArray *supplierCategories = [recieveDictionary objectForKey:@"SupplierCategories"];
    if(usingPickerView == @"addressPicker")
    {
        NSInteger rows = [addressPickerView selectedRowInComponent:0];
        NSString *strs = [NSString stringWithFormat:@"%@",[addressTestData objectAtIndex:rows]];
        [addBtn setTitle:strs forState:UIControlStateNormal];
        [addBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    }
    else if(usingPickerView == @"typePicker")
    {
        NSInteger rows = [typePickerView selectedRowInComponent:0];
        SupplierCategory *supplierCategory=[supplierCategories objectAtIndex:rows];
        NSString *strs = [NSString stringWithFormat:@"%@",supplierCategory.supplierCategoryName];
        [typeBtn setTitle:strs forState:UIControlStateNormal];
        [typeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
        supplierCategoryTag = supplierCategory.supplierCategoryId;
    }
    else if(usingPickerView == @"shopHoursPicker")
    {
        NSInteger rows = [shopHoursPickerView selectedRowInComponent:0];
        NSString *strs = [NSString stringWithFormat:@"%@",[shopHoursTestData objectAtIndex:rows]];
        [timeBtn setTitle:strs forState:UIControlStateNormal];
        [timeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    }
    currentPage = 1;
    isEnd = false;
    if (manager == nil) {
        manager = [[SupplierManager alloc] init];
    }
    NSString *road = addBtn.titleLabel.text;
    NSString *isSelling = @"";
    if([road isEqualToString: @"地区"]){
        road = nil;
    }
    if([timeBtn.titleLabel.text isEqualToString: @"营业中"]){
        isSelling = @"y";
    }
    else if([timeBtn.titleLabel.text isEqualToString: @"打烊"]){
        isSelling = @"n";
    }
    else{
        isSelling = nil;
    }
    
    NSString *supplierCategoryTagString=[NSString stringWithFormat: @"%d", supplierCategoryTag];
    NSString *currentPageString=[NSString stringWithFormat: @"%d", currentPage];
   
    if([appDelegate status]){
        //联网
        suppliers = [[manager getSupplier:[NSString stringWithFormat:@"%d",supplierCategoryTag] pageIndex:currentPage road:road isSelling:isSelling] retain];
        //添加到本地
        [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:supplierCategoryTagString sPage:currentPageString];
    }
    else{
        //离线
        suppliers=[[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:supplierCategoryTagString sPage:currentPageString road:road isSelling:isSelling] retain];
    }
    if (suppliers == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
    }
    [tableViews reloadData];
    [self hiddenPickerView];
}
//点击取消触发
-(IBAction)pickerCancelButtonPress:(id)sender
{
    [self hiddenPickerView];
}


//加载本地nib文件
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {   
    
    UIView *tbView = [[UIView alloc] initWithFrame:CGRectMake(0, 28, 320,485)];  
    //自定识别头及高度  
    tbView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight;  
    tbView.backgroundColor = [UIColor whiteColor];  
    //将view添加到主窗体  
    [self.view addSubview:tbView]; 
    
    tableViews=[[UITableView alloc] initWithFrame:CGRectMake(0, 28, 320, 485)];  
    tableViews.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight;  
    tableViews.backgroundColor=[UIColor whiteColor];  
    //添加到view窗体上  
    [tbView addSubview:tableViews];  
    [tbView release];
    tableViews.delegate=self;  
    tableViews.dataSource=self; 
    
    
    //初始化导航栏
    [self initNav];
    //初始化选择条件按钮
    [self initTypeBtn];
    //初始化picker
    [self initPickers];
    
    
    //设置视图title
    self.title=@"商家列表";
    //初始化3个pickerView控件
    [self addAddressPickerView];
    [self addTypePickerView];
    [self addShopHoursPickerView];
    //导入测试数据
    NSArray *tmpAddressTestData = [[NSArray alloc] initWithObjects:@"地区",@"市政府周边", @"步行街周边",@"狮标周边",@"鸳鸯池周边",@"华侨医院周边",@"服装城周边", nil];
    self.addressTestData = tmpAddressTestData;
    [tmpAddressTestData release];
    
    NSArray *tmpShopHoursTestData = [[NSArray alloc] initWithObjects:@"营业情况",@"营业中", @"打烊", nil];    
    self.shopHoursTestData = tmpShopHoursTestData;
    [tmpShopHoursTestData release]; 
    
    [super viewDidLoad];
}

- (void)backButtonPressd:(id)sender{
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    //设置显示导航栏
    self.navigationController.navigationBarHidden = NO; 
    
    
    
}

/*************************/ 
/*       商家列表视图       */
/**************************/

//返回表试图分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [suppliers count];
}




//设置表试图每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index=indexPath.row;
    Supplier *supplier=[suppliers objectAtIndex:index];
    static NSString *CellIdentifier = @"CustomCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  
    
	if(cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        //设置单元格背景图片
        UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"011s.png"]];
        cell.backgroundView = bgImageView;    
        [bgImageView release];
    }    

    
    UICustomImageView *imageView = (UICustomImageView *)[cell.contentView viewWithTag:100];
    if (imageView == nil) {
        UIImageView* imgBg=[[UIImageView alloc] initWithFrame:CGRectMake(5,5,85,85)];
        [imgBg setImage:[UIImage imageNamed:@"ImgBg.png"]];  
        [imgBg setUserInteractionEnabled:YES];  
        [cell.contentView addSubview:imgBg];
        [imgBg release];
        
        imageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(9, 8, 77, 77)];
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        [imageView setUserInteractionEnabled:NO];
        [imageView setTag:100];
        [cell.contentView addSubview:imageView];
        [imageView release];
    }
    [imageView setImage:nil];
    [imageView setImageURL:supplier.imgUrl];
    imageView.image = [PublicFunction resizeImage:imageView.image newSize:CGSizeMake(60,60)];
    
    
    UILabel *shopNameLabel = (UILabel *)[cell.contentView viewWithTag:200];
    if (shopNameLabel == nil) {
        shopNameLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        shopNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 7, 200, 16)];
        [shopNameLabel setText:supplier.supplierName];
        [shopNameLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [shopNameLabel setBackgroundColor:[UIColor clearColor]];
        shopNameLabel.tag = 200;
        [cell.contentView addSubview:shopNameLabel];
        [shopNameLabel release];
    }
    //设置商铺名长度
    if(supplier.supplierName.length>7){
        NSString *supplierNameShort = [supplier.supplierName substringToIndex:7];
        [supplier setSupplierName:supplierNameShort];
    }
    [shopNameLabel setText:supplier.supplierName];
    
    UILabel *shopDescLabel = (UILabel *)[cell.contentView viewWithTag:204];
    if (shopDescLabel == nil) {
        shopDescLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 33, 120, 14)];
        shopDescLabel.font=[UIFont fontWithName:@"Helvetica" size:14];
        [shopDescLabel setBackgroundColor:[UIColor clearColor]];
        shopDescLabel.tag = 204;
        [cell.contentView addSubview:shopDescLabel];
        [shopDescLabel release];
    }
    [shopDescLabel setText:supplier.desc];
    
    UILabel *shopTypeLable=(UILabel *)[cell.contentView viewWithTag:202];
    if (shopTypeLable == nil) {
        shopTypeLable = [[UILabel alloc] initWithFrame:CGRectMake(95, 51, 200, 14)];
        shopTypeLable.font=[UIFont fontWithName:@"Helvetica" size:14];
        [shopTypeLable setBackgroundColor:[UIColor clearColor]];
        shopTypeLable.tag = 202;
        [cell.contentView addSubview:shopTypeLable];
        [shopTypeLable release];
    }
     NSString *supplierCategoryName = [NSString stringWithFormat:@"【%@】",supplier.supplierCategoryName];
    [shopTypeLable setText:supplierCategoryName];
    
    UILabel *shopAvgPriceLable=(UILabel *)[cell.contentView viewWithTag:203];
    if (shopAvgPriceLable == nil) {
        shopAvgPriceLable = [[UILabel alloc] initWithFrame:CGRectMake(180, 51, 100, 14)];
        shopAvgPriceLable.font=[UIFont fontWithName:@"Helvetica" size:14];
        //自定义颜色
        [shopAvgPriceLable setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
        
        [shopAvgPriceLable setBackgroundColor:[UIColor clearColor]];
        shopAvgPriceLable.tag = 203;
        [cell.contentView addSubview:shopAvgPriceLable];
        [shopAvgPriceLable release];
    }
    NSString *avgPrice=[NSString stringWithFormat:@"人均: %.2f",supplier.avgPrice];
    [shopAvgPriceLable setText:avgPrice];
    
    UILabel *shopAddressLabel = (UILabel *)[cell.contentView viewWithTag:201];
    if (shopAddressLabel == nil) {
        shopAddressLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 69, 200, 14)];
        shopAddressLabel.font=[UIFont fontWithName:@"Helvetica" size:14];
        [shopAddressLabel setBackgroundColor:[UIColor clearColor]];
        shopAddressLabel.tag = 201;
        [cell.contentView addSubview:shopAddressLabel];
        [shopAddressLabel release];
    }

    [shopAddressLabel setText:supplier.address];

    UIButton *phoneButton = (UIButton *)[cell.contentView viewWithTag:300];
    if (phoneButton == nil) {
        phoneButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
        [phoneButton setFrame:CGRectMake(240, 7, 50, 55)];
        UIImage *image = [UIImage imageNamed:@"phoneImg.png"]; 
        [phoneButton setBackgroundImage:image forState:UIControlStateNormal]; 
        phoneButton.tag = 300;
        [phoneButton addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:phoneButton];
        //点击拨号按钮直接拨号
    }
    
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    cell.tag = supplier.supplierId;
    
    return cell;
    
}

//定义点击拨号按钮时的操作 
- (void)callAction:(id)sender event:(id)event{ 
    NSSet *touches = [event allTouches]; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:tableViews]; 
    NSIndexPath *indexPath = [tableViews indexPathForRowAtPoint: currentTouchPosition]; 
    if (indexPath == nil) { 
        return; 
    } 
    NSUInteger  row = [indexPath row]; 
    Supplier *rowData = [suppliers objectAtIndex:row]; 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    if(rowData.phone.length != 0){
        [alert addButtonWithTitle:rowData.phone];
    }
    if(rowData.phone2.length != 0){
        [alert addButtonWithTitle:rowData.phone2];
    }
    if(rowData.telephone.length != 0){
        [alert addButtonWithTitle:rowData.telephone];
    }
    if(rowData.telephone2.length != 0){
        [alert addButtonWithTitle:rowData.telephone2];
    } 
    alert.tag = 1;
	[alert show];
	[alert release];
    
}

//根据被点击按钮的索引处理点击事件  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串 
        NSString *phoneNumber = [NSString stringWithFormat:@"tel://%@",number]; 
        //拨号 
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; 
    }
}



//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
    //无点击picker确定，跳转页面，隐藏picker
    [self hiddenPickerView];
    CustomCell *cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
    NSString *supplierId = [NSString stringWithFormat:@"%d",cell.tag];
    manager = [[SupplierManager alloc] init];
    Supplier *supplierDetail;
    if([appDelegate status]){
        //联网
    supplierDetail = [manager getSupplierDetailById:supplierId];
    }
    else{
        //离线
        supplierDetail=[fmdbSupplierManager getSupplierDetailByIdFromLoc:supplierId];
    }

    if (supplierDetail == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该商家的详细信息" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        return;
    }
    
    //创建新的试图并将试图推入栈中
    DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]initWithNibName:@"DetailShopViewController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:detailShopViewController];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
    [dictionary setObject:supplierId forKey:@"supId"];
    [dictionary setObject:supplierDetail forKey:@"Supplier"];
    
    [detailShopViewController setRecieveDictionary:dictionary];
    
    [detailShopViewController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: detailShopViewController animated:YES];
    [theNavController release];
    
    
   
}



//设置表试图行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath   
{
    return 95;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 80;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NSArray *nils = [[NSBundle mainBundle]loadNibNamed:@"RefreshView" owner:self options:nil];
    refreshView = [nils objectAtIndex:0];
    [refreshView setupWithOwner:tableView delegate:self];
    refreshView.isPullUp = YES;
    refreshView.hidden = YES;
    return refreshView;
}

/************************/ 
/*     索搜类型选取器      */
/************************/



//显示地区选取器
-(void) showAddressPickerView {
    //将所有选取器和横条都隐藏
    [self hiddenPickerView];
    /************************/ 
    /*     选取器动画效果      */
    /************************/
    //显示地区选取器，隐藏其他
    //开始动画
    [UIView beginAnimations: @"Animation" context:nil];
    //设定动画持续时间
    [UIView setAnimationDuration:0.3]; 
    //生成选取器，并向上拉动
    addressPickerView.frame = CGRectMake(0, 240, 320, 460);
    tiaoImageView.frame = CGRectMake(0, 212, 320, 37);
    submitButton.frame = CGRectMake(267, 215, 48, 25);
    cancelButton.frame = CGRectMake(7, 215, 48, 25);
    //动画结束
    [UIView commitAnimations]; 
    [addressPickerView setHidden:NO];
    //显示确定和取消按钮的横条
    [submitButton setHidden:NO];
    [cancelButton setHidden:NO];
    [tiaoImageView setHidden:NO];
}

//显示类型选取器
-(void) showTypePickerView {
    //将所有选取器和横条都隐藏
    [self hiddenPickerView];
    //显示类型选取器
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3]; 
    typePickerView.frame = CGRectMake(0, 240, 320, 460);
    submitButton.frame = CGRectMake(267, 215, 48, 25);
    cancelButton.frame = CGRectMake(7, 215, 48, 25);
    tiaoImageView.frame = CGRectMake(0, 212, 320, 37);
    [UIView commitAnimations]; 
    [typePickerView setHidden:NO];
    //显示确定和取消按钮的横条
    [submitButton setHidden:NO];
    [cancelButton setHidden:NO];
    [tiaoImageView setHidden:NO];
}

//显示营业时间选取器
-(void) showShopHoursPickerView {
    //将所有选取器和横条都隐藏
    [self hiddenPickerView];
    //显示营业时间选取器
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3]; 
    shopHoursPickerView.frame = CGRectMake(0, 240, 320, 460);
    submitButton.frame = CGRectMake(267, 215, 48, 25);
    cancelButton.frame = CGRectMake(7, 215, 48, 25);
    tiaoImageView.frame = CGRectMake(0, 212, 320, 37);
    [UIView commitAnimations];
    [shopHoursPickerView setHidden:NO];
    //显示确定和取消按钮的横条
    [submitButton setHidden:NO];
    [cancelButton setHidden:NO];
    [tiaoImageView setHidden:NO];
}

//隐藏全部选取器
-(void) hiddenPickerView {
    //隐藏确定和取消按钮的横条
    [submitButton setHidden:YES];
    [cancelButton setHidden:YES];
    [tiaoImageView setHidden:YES];
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3]; 
    addressPickerView.frame = CGRectMake(0, 460, 320, 460);
    submitButton.frame = CGRectMake(261, 428, 48, 28);
    cancelButton.frame = CGRectMake(7, 428, 48, 28);
    tiaoImageView.frame = CGRectMake(0, 423, 320, 37);
    [UIView commitAnimations]; 
    
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3]; 
    typePickerView.frame = CGRectMake(0, 460, 320, 460);
    [UIView commitAnimations]; 
    
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3]; 
    shopHoursPickerView.frame = CGRectMake(0, 460, 320, 460);
    [UIView commitAnimations];
}


//点击显示选取器
- (IBAction)showPickerViewAction:(id)sender {
    //取得按钮tag
    NSInteger type=[sender tag];    
    if(type==addressTag)
    {
        usingPickerView = @"addressPicker";
        [self showAddressPickerView];
    }
    else if(type==typeTag)
    {
        usingPickerView = @"typePicker";
        [self showTypePickerView];
    }
    else
    {
        usingPickerView = @"shopHoursPicker";
        [self showShopHoursPickerView];
    }
}

//返回每个组件上的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(pickerView==addressPickerView)
    {
        return [addressTestData count];
    }
    else if(pickerView==typePickerView) 
    {
        NSArray *supplierCategories = [recieveDictionary objectForKey:@"SupplierCategories"];
        return [supplierCategories count];
    }
    else
    {
        return [shopHoursTestData count];
    }
}

//返回有pickerview的组件数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

//pickerview的值
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSArray *supplierCategories = [recieveDictionary objectForKey:@"SupplierCategories"];
    SupplierCategory *supplierCategory=[supplierCategories objectAtIndex:row];
    if(pickerView==addressPickerView)
    {
        return [addressTestData objectAtIndex:row];
    }
    else if(pickerView==typePickerView)
    {
        return supplierCategory.supplierCategoryName;
    }
    else
    {
        return [shopHoursTestData objectAtIndex:row];
    }
}

//当你选中pickerview的某行时会调用该函数。
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    
}
//自定义pickerview使内容显示在每行的中间，默认显示在每行的左边（(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component）
//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
//    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)] autorelease];
//	if (row == 0) {
//        label.text=@"nan";
//	}else {
//		label.text = @"女";
//	}
//	[label setTextAlignment:UITextAlignmentCenter];
//    return label;
//}



//设置指定组件上每行的宽度
/*
 -(void)pickerView:(UIPickerView *)thePickerView widthForComponet:component {
 
 }
 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [self setActivityIndicatorView:nil];
    [self setAddressTestData:nil];
    [self setShopHoursTestData:nil];
    [self setTypePickerView:nil];
    [self setAddressPickerView:nil];
    [self setShopHoursPickerView:nil];
}

- (void)dealloc {
    [addressTestData release];
    [shopHoursTestData release];
    [tableViews release];
    [typeBtn release];
    [timeBtn release];
    if (manager!=nil) {
        [manager release];
    }
    [suppliers release];
    [refreshView release];
    [submitButton release];
    [cancelButton release];
    [tiaoImageView release];
    //    [super dealloc];
}

// 停止，可以触发自己定义的停止方法
- (void)stopLoading {
    [tableViews reloadData];
    [refreshView stopLoading];
}
// 开始，可以触发自己定义的开始方法
- (void)startLoading {
    refreshView.hidden = NO;
    [refreshView startLoading];
    // 模拟3秒后停止
    
    if (!isEnd) {
        currentPage++;
        if (manager == nil) {
            manager = [[SupplierManager alloc] init];
        }
        NSArray *newSuppliers;
        NSString *supplierCategoryTagString=[NSString stringWithFormat: @"%d", supplierCategoryTag];
        NSString *currentPageString=[NSString stringWithFormat: @"%d", currentPage];
        
        NSString *road = addBtn.titleLabel.text;
        NSString *isSelling = @"";
        if([road isEqualToString: @"地区"]){
            road = nil;
        }
        if([timeBtn.titleLabel.text isEqualToString: @"营业中"]){
            isSelling = @"y";
        }
        else if([timeBtn.titleLabel.text isEqualToString: @"打烊"]){
            isSelling = @"n";
        }
        else{
            isSelling = nil;
        }

        if([appDelegate status]){
            //联网
            newSuppliers = [manager getSupplier:[NSString stringWithFormat:@"%d",supplierCategoryTag] pageIndex:currentPage road:road isSelling:isSelling];
            //添加到本地
            [fmdbSupplierManager insertSupplierByCategoryId:newSuppliers supplierCategoryId:supplierCategoryTagString sPage:currentPageString];
        }
        else{
            //离线
            newSuppliers=[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:supplierCategoryTagString sPage:currentPageString road:road isSelling:isSelling];
        }
        if (newSuppliers != nil) {
            suppliers = [[suppliers arrayByAddingObjectsFromArray:newSuppliers] retain];
        }else{
            isEnd = YES;
        }
    }
    
    [self performSelector:@selector(stopLoading) withObject:nil afterDelay:3];
}
// 刷新
- (void)refresh {
    [self startLoading];
}
#pragma mark - RefreshViewDelegate
- (void)refreshViewDidCallBack {
    [self refresh];
}
#pragma mark - UIScrollView 
// 刚拖动的时候
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [refreshView scrollViewWillBeginDragging:scrollView];
}
// 拖动过程中
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [refreshView scrollViewDidScroll:scrollView];
}
// 拖动结束后
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [refreshView scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}
@end
